package com.css.zfzx.sjcj.modules.service;

import com.css.zfzx.sjcj.common.MenuInfoEnum;
import com.css.zfzx.sjcj.modules.pojo.DivisionData;
import com.css.zfzx.sjcj.modules.pojo.RequestParams;
import com.css.zfzx.sjcj.modules.pojo.RespondParams;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class HandlerService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    ServiceLocator serviceLocator;

    public List<RespondParams> handlerData(RequestParams params) {
        Map<String, CommonInterfaceService> map = serviceLocator.getMap();
        List<RespondParams> respondParamsList = new ArrayList<>();
        for (String serviceName : map.keySet()) {
            CommonInterfaceService serviceImpl = map.get(serviceName);
            RespondParams respondParams = serviceImpl.dataStatistics(params);
            if (!Objects.isNull(respondParams)) {
                respondParamsList.add(respondParams);
                //System.out.println(respondParams);
            }
        }
        //System.out.println(respondParamsList);
        return respondParamsList;
    }

    public void handlerExportData(HttpServletResponse response, RequestParams params) {
        List<RespondParams> respondParamsList = handlerData(params);
        try {
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            String name = dateStr + "进度报告.xlsx";
            //response.setContentType("application/octet-stream ");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Connection", "close"); // 表示不能用浏览器直接打开
            //response.setHeader("Accept-Ranges", "bytes");// 告诉客户端允许断点续传多线程连接下载
            response.setHeader("Content-Disposition", "attachment;fileName="
                    + new String(name.getBytes("GB2312"), "ISO8859-1"));
            response.setCharacterEncoding("UTF-8");

            HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件
            // 样式设置
            HSSFCellStyle columnHeadStyle = workbook.createCellStyle();
            columnHeadStyle.setFillPattern(FillPatternType.NO_FILL); // 背景
            columnHeadStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex()); // 背景色AQUA.getIndex()
            columnHeadStyle.setBorderBottom(BorderStyle.THIN); // 下边框
            columnHeadStyle.setBorderLeft(BorderStyle.THIN);// 左边框
            columnHeadStyle.setBorderTop(BorderStyle.THIN);// 上边框
            columnHeadStyle.setBorderRight(BorderStyle.THIN);// 右边框
            columnHeadStyle.setAlignment(HorizontalAlignment.LEFT);//左右居中
            columnHeadStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);// 上下居中
            columnHeadStyle.setWrapText(true);//自动换行

            HSSFSheet sheet = workbook.createSheet("进度报告");
            sheet.setColumnWidth(0, 6000);
            String[] sheetHeadTitle = new String[respondParamsList.size() + 1];
            sheetHeadTitle[0] = "任务名称";
            ConvertUtils.register(new DateConverter(null), java.util.Date.class);
            for (int i = 0; i < respondParamsList.size() + 1; i++) {
                if (i != respondParamsList.size()) {
                    sheetHeadTitle[i + 1] = MenuInfoEnum.getInstanceByName(respondParamsList.get(i).getMenuId()).getMenuName();
                }
                HSSFRow row0 = sheet.createRow(i);
                row0.setHeightInPoints(30);
                RespondParams respondParams = null;
                if (i == 0) {
                    respondParams = respondParamsList.get(i);
                } else {
                    respondParams = respondParamsList.get(i - 1);
                }
                List<DivisionData> divisionDataList = respondParams.getDivisionDataList();
                for (int t = 0; t < divisionDataList.size() + 1; t++) {
                    HSSFCell cel0_1 = row0.createCell(t);
                    if (t == 0) {
                        cel0_1.setCellValue(new HSSFRichTextString(sheetHeadTitle[i]));
                    } else if (i == 0 && t != 0) {
                        cel0_1.setCellValue(new HSSFRichTextString(divisionDataList.get(t - 1).getDivision()));
                    } else if (i != 0 && t != 0) {
                        if (!"1".equals(params.getDataType())) {
                            cel0_1.setCellValue(new HSSFRichTextString(divisionDataList.get(t - 1).getCollectionCount()));
                        } else {
                            cel0_1.setCellValue(new HSSFRichTextString(divisionDataList.get(t - 1).getQualityCount()));
                        }
                    }
                    cel0_1.setCellStyle(columnHeadStyle);
                }
                sheet.autoSizeColumn((short) i);//宽度自适应
            }

            OutputStream out = response.getOutputStream();
            workbook.write(out);
            // ByteArrayOutputStream bos = new ByteArrayOutputStream();
            // workbook.write(bos);
            // bos.writeTo(out);
            if (out != null) {
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(respondParamsList);
    }
}
